package org.example.springchatroom.component;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/9/17
 * Time: 14:31
 */
@Data
@Component
@Slf4j
public class OnlineUserManager {
    private ConcurrentHashMap<Integer, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    public void online(Integer userId,WebSocketSession session){
        if (sessionMap.get(userId) != null) {
            return;
        }
        sessionMap.put(userId, session);
        log.info("online用户上线,userId:{}",userId);
    }

    public void offline(Integer userId,WebSocketSession session){
        WebSocketSession webSocketSession = sessionMap.get(userId);
        if (webSocketSession == null) {
            return;
        }
        if (webSocketSession == session) {
            sessionMap.remove(userId);
            log.info("offline用户下线,userId:{}",userId);
        }
    }

    public WebSocketSession getSession(Integer userId){
        return sessionMap.get(userId);
    }
}
